package com.example.demo.context;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonIgnore;

public class BaseContext implements Serializable{
	/**
     * 自定义上下文对象
     */
    @JsonIgnore
    private Serializable extContext;

    /**
     * 其他上下文数据，map存储
     */
    private Map<String, Serializable> contextData = new HashMap<String, Serializable>();

    @JsonIgnore
    public Serializable getExtContext() {
        return extContext;
    }

    @JsonIgnore
    public void setExtContext(Serializable extContext) {
        this.extContext = extContext;
        put("context_ext", extContext);
    }

    /**
     * 根据键值获取上下文数据
     * @param key
     * @return
     */
    public Object get(String key) {
        return this.contextData.get(key);
    }

    /**
     * 存储上下文数据
     * @param key
     * @param value
     */
    public void put(String key, Serializable value) {
        this.contextData.put(key, value);
    }

    /**
     * 判断上下文是否存在
     * @param key
     * @return
     */
    public boolean hasKey(String key){
        return this.contextData.containsKey(key);
    }

    /**
     * 删除指定上下文
     * @param key
     * @return
     */
    public void removeKey(String key){
        this.contextData.remove(key);
    }

    /**
     * 清空上下文
     */
    public void clear(){
        this.contextData.clear();
        this.extContext = null;
    }

    public Map<String, Serializable> getContextData() {
        return contextData;
    }

    public void setContextData(Map<String, Object> contextData) {
        for (Map.Entry<String, Object> entry : contextData.entrySet()) {
            String key = entry.getKey();
            if ("_".equals(key)) {
                continue;
            }
            Object value = entry.getValue();
            if (value instanceof Serializable) {
                this.contextData.put(key, (Serializable)value);
            }
        }
    }
}
